﻿using Geek.Server.Core.Hotfix;
using Geek.Server.Core.Serialize;
using Microsoft.AspNetCore.Http;
using NLog;

namespace Geek.Server.Core.Net.Http
{
    internal class HttpHandler
    {
        static readonly Logger LOGGER = LogManager.GetCurrentClassLogger();

        private const string ROUTE_QUERY_KEY = "api";

        private static async Task<HttpResponse> HandleRequestInner(HttpContext context)
        {
            try
            {
                var ip = context.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
                string url = context.Request.PathBase + context.Request.Path;
                LOGGER.Info("收到来自[{}]的HTTP请求. 请求url:[{}]", ip, url);

                if (!Settings.AppRunning)
                    return HttpResponse.Create(1000006); // 服务器已经关闭

                if (!context.Request.Query.TryGetValue(ROUTE_QUERY_KEY, out var routeValues))
                    return HttpResponse.Create(1000003); // 参数错误

                var route = routeValues[0];
                if (string.IsNullOrEmpty(route))
                    return HttpResponse.Create(1000003); // 参数错误

                var handler = HotfixMgr.GetHttpHandler(route);
                if (handler == null)
                {
                    LOGGER.Warn($"无效的http路由:[{route}]");
                    return HttpResponse.Create(1000001); // 无效的路由
                }

                var requestBody = string.Empty;

                if (context.Request.Method.Equals("POST") && context.Request.ContentLength.HasValue && context.Request.ContentLength.Value > 0)
                {
                    var headCType = context.Request.ContentType;
                    if (string.IsNullOrEmpty(headCType))
                        return HttpResponse.Create(1000003); // 参数错误
                    
                    if (!context.Request.HasJsonContentType())
                        return HttpResponse.Create(1000003); // 参数错误

                    using var reader = new StreamReader(context.Request.Body);
                    requestBody = await reader.ReadToEndAsync();
                }

                return await Task.Run(() => handler.Action(ip, requestBody));
            }
            catch (Exception e)
            {
                LOGGER.Error("执行http异常. {} {}", e.Message, e.StackTrace);
                return HttpResponse.Create(1000002); // 内部错误
            }
        }

        /// <summary>
        /// 统一约束
        /// </summary>
        public static async Task HandleRequest(HttpContext context)
        {
            context.Response.Headers.Add("content-type", "text/html;charset=utf-8");
            var response = await HandleRequestInner(context);
            await context.Response.WriteAsync(response.ToJsonStr());
        }
    }
}